package com.gtenacg.cartoonservice.service.impl;

import com.gtenacg.cartoonservice.mapper.AdminMapper;
import com.gtenacg.cartoonservice.pojo.model.Admin;
import com.gtenacg.cartoonservice.service.AdminService;
import com.gtenacg.cartoonservice.util.EmailUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;


@Service
@RequiredArgsConstructor
public class AdminServiceImpl implements AdminService {

    final AdminMapper adminMapper;
    final EmailUtil emailUtil;

    @Override
    public List<Admin> list() {
        return adminMapper.list();
    }

    @Override
    public Admin getById(Integer id) {
        return adminMapper.getById(id);
    }

    @Override
    public Admin login(Admin admin) {
        admin = adminMapper.login(admin);
        return admin;
    }

    @Override
    public Integer insert(Admin admin) throws DuplicateKeyException {
        adminMapper.insert(admin);
        return admin.getId();
    }

    @Override
    public void update(Admin admin) {
        adminMapper.update(admin);
    }

    @Override
    public void delete(List<Integer> ids) {
        adminMapper.delete(ids);
    }

    @Override
    public void resetPassword(Admin admin) {
        // 生成密码
        String pwd = UUID.randomUUID().toString().replace("-", "").substring(0, 12);
        String content = "您的邮箱所绑定的 GTenACG 管理员账号: " + admin.getName() + "，密码已被重置，临时密码已发送，请尽快修改密码！！！\n"
                + " 临时密码：[ " + pwd + " ] ";

        // 发送邮件
        emailUtil.sendEmail(admin.getEmail(), "GTenACG 管理员密码重置", content);
        // 写入数据库
        admin.setPassword(DigestUtils.md5Hex(pwd));
        adminMapper.update(admin);
    }


}
